import Message from 'element-ui/lib/message';
import MessageBox from 'element-ui/lib/message-box';
import { isObj } from './../utils/whether'

// 默认配置
const option = { title: '提示', content: '此操作将提交当前表单内容, 是否继续?' }
const msgOptions = { confirmButtonText: '确认', cancelButtonText: '取消', showCancelButton: true, center: true, type: 'warning' };
const defaultConfig = { prop: 'id', data: 'formData', show: 'formVisible', loading: "formLoading" };
const confirmDialog = async (data) => { try { return data ? await MessageBox.confirm(option.content, option.title, msgOptions) : null } catch (error) { return Message.warning('已取消操作！') } }


/**
 *  提交表单装饰器
 * @param {*} msg 提交后提示信息
 * @param {*} option 提交确认弹窗
 * @param {*} showConfirm 显示弹窗框， 默认为false
 */
export default function (msg = '', option = {}, showConfirm = false) {
  const params = Object.assign(defaultConfig, option);
  return function (target, propertyKey, descriptor) {
    const method = descriptor.value;
    descriptor.value = async function (form = {}, ...args) {
      const that = this._isVue ? this : target;
      const data = that[params.data] || {}
      const isEdit = Boolean(data && data[option.prop]) // 提交表单的状态（编辑|新增）
      const message = isEdit ? '修改成功' : '添加成功'  // 提交成功提示信息信息
      const formData = isObj(form) ? form : {}
      await confirmDialog(showConfirm)
      this[params.loading] = true;
      try {
        await method.apply(that, [form, data[option.prop], data])
        this[params.data] = {};
        this[params.show] = false;
        this[params.loading] = false;
        Message.success(msg || message);
      } catch (error) {
        this[params.loading] = false;
        console.error(error)
      }
    };
  };
}
